Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraEditors.Repository

'--- Created Date On : 15-Nov-2008 (Pinak)

Public Class frmUtilityUserAccess
    Public mlngRecordID As Long
    Public blnAdd As Boolean
    Public blnEdit As Boolean
    Public blnDelete As Boolean
    Public blnLocked As Boolean
    Dim blnUnload As Boolean
    Dim mblnChanged, mblnAccessChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mstrMode As String

    Public mstrMenuList(16)() As String    'Keeps menu details (Jagged Arrays)

    Private Sub frmMasterCompanyDetails_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False
                PopulateLookupDX(lkUserSelect, "Login Name", "UserId", "tblUsers", "UserId,LoginName [Login Name]", "", "LoginName", False, "", 200, False)
                'Check for login. If logged user is doctor then user level should be Nurse n Receptionist.
                Dim UserCriteria As String = IIf(gintUserLevelId = 2, " UserLevelId=3 OR UserLevelId=4 ", String.Empty)
                PopulateLookupDX(lkUserLevel, "User Level", "UserLevelId", "LtblUserLevel", "UserLevelId, UserLevel [User Level]", UserCriteria, "UserLevel")
                'lkUserSelect.ItemIndex = 0
                lkUserSelect.EditValue = CInt(gintUserID)
                lkUserSelect_TextChanged(Nothing, Nothing)
            End If
        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmUtilityUserAccess_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Me.Dispose()
    End Sub

    Private Sub frmMasterCompanyDetails_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            Dim intUnload As DialogResult

            If (mblnChanged = True And mstrMode <> "") Or mblnAccessChanged = True Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    If mblnChanged = True Then
                        blnUnload = True
                        If blnSaveRecords() = False Then
                            e.Cancel = True
                            blnUnload = False
                            Exit Sub
                        End If
                    End If
                    If mblnAccessChanged = True Then
                        Call btnSetAP_Click(Nothing, Nothing)
                    End If
                    mblnChanged = False
                    mblnAccessChanged = False
                End If
            End If
            blnUnload = False
        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub SetData(ByVal rowHandle As Integer)

        Try
            mblnAccessChanged = True
            'dt.Rows.Add(2, str[0].ToString(), 2, 2, 2, 1, str[1].ToString());

            If gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "0" Then

                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                For i As Integer = rowHandle To gdvRecords.RowCount - 1
                    If (i <> rowHandle And gdvRecords.GetRowCellValue(i, Group).ToString() = "0") Then Exit For
                    gdvRecords.SetRowCellValue(i, FormSet, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))

                    If (gdvRecords.GetRowCellValue(i, Group).ToString() = "1") Then

                        gdvRecords.SetRowCellValue(i, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Delete, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.UpdateCurrentRow()

                    ElseIf (gdvRecords.GetRowCellValue(i, Group).ToString() = "2") Then

                        gdvRecords.SetRowCellValue(i, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Edit, 3)
                        gdvRecords.SetRowCellValue(i, Delete, 3)
                        gdvRecords.UpdateCurrentRow()

                    ElseIf (gdvRecords.GetRowCellValue(i, Group).ToString() = "3") Then

                        gdvRecords.SetRowCellValue(i, Add, 3)
                        gdvRecords.SetRowCellValue(i, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Delete, 3)
                        gdvRecords.UpdateCurrentRow()

                    ElseIf (gdvRecords.GetRowCellValue(i, Group).ToString() = "4") Then

                        gdvRecords.SetRowCellValue(i, Add, 3)
                        gdvRecords.SetRowCellValue(i, Edit, 3)
                        gdvRecords.SetRowCellValue(i, Delete, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.UpdateCurrentRow()

                    ElseIf (gdvRecords.GetRowCellValue(i, Group).ToString() = "5") Then

                        gdvRecords.SetRowCellValue(i, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                        gdvRecords.SetRowCellValue(i, Delete, 3)
                        gdvRecords.UpdateCurrentRow()
                    End If
                Next

            ElseIf (gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "1") Then

                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                gdvRecords.SetRowCellValue(rowHandle, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Delete, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.UpdateCurrentRow()

            ElseIf (gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "2") Then

                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                gdvRecords.SetRowCellValue(rowHandle, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Edit, 3)
                gdvRecords.SetRowCellValue(rowHandle, Delete, 3)
                gdvRecords.UpdateCurrentRow()

            ElseIf (gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "3") Then

                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                gdvRecords.SetRowCellValue(rowHandle, Add, 3)
                gdvRecords.SetRowCellValue(rowHandle, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Delete, 3)
                gdvRecords.UpdateCurrentRow()

            ElseIf (gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "4") Then

                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                gdvRecords.SetRowCellValue(rowHandle, Add, 3)
                gdvRecords.SetRowCellValue(rowHandle, Edit, 3)
                gdvRecords.SetRowCellValue(rowHandle, Delete, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.UpdateCurrentRow()

            ElseIf (gdvRecords.FocusedColumn Is FormSet And gdvRecords.GetRowCellValue(rowHandle, Group).ToString() = "5") Then
                If (gdvRecords.GetRowCellValue(rowHandle, FormSet).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                Else
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                End If
                gdvRecords.SetRowCellValue(rowHandle, Add, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Edit, Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, FormSet)))
                gdvRecords.SetRowCellValue(rowHandle, Delete, 3)
                gdvRecords.UpdateCurrentRow()
            ElseIf (gdvRecords.GetRowCellValue(rowHandle, Group).ToString() <> "0" And gdvRecords.FocusedColumn Is Add Or gdvRecords.FocusedColumn Is Edit Or gdvRecords.FocusedColumn Is Delete) Then

                Dim iVal As Integer = Convert.ToInt32(gdvRecords.GetRowCellValue(rowHandle, gdvRecords.FocusedColumn))
                If (iVal = 1) Then
                    gdvRecords.SetRowCellValue(rowHandle, gdvRecords.FocusedColumn, 2)
                ElseIf (iVal = 2) Then
                    gdvRecords.SetRowCellValue(rowHandle, gdvRecords.FocusedColumn, 1)
                End If
                If (gdvRecords.GetRowCellValue(rowHandle, Add).ToString() = "1" Or gdvRecords.GetRowCellValue(rowHandle, Edit).ToString() = "1" Or gdvRecords.GetRowCellValue(rowHandle, Delete).ToString() = "1") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 1)
                ElseIf (gdvRecords.GetRowCellValue(rowHandle, Add).ToString() = "2" And gdvRecords.GetRowCellValue(rowHandle, Edit).ToString() = "2" And gdvRecords.GetRowCellValue(rowHandle, Delete).ToString() = "2") Then
                    gdvRecords.SetRowCellValue(rowHandle, FormSet, 2)
                End If


            End If


        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub populateInGrid()

        Dim line As String = ""
        Try

            Dim dt As DataTable
            dt = New DataTable("temp")
            dt.Columns.Add("Set", GetType(Integer))
            dt.Columns.Add("FormName", GetType(String))
            dt.Columns.Add("Add", GetType(Integer))
            dt.Columns.Add("Edit", GetType(Integer))
            dt.Columns.Add("Delete", GetType(Integer))
            dt.Columns.Add("Group", GetType(Integer))
            dt.Columns.Add("FormText", GetType(String))

            If (System.IO.File.Exists(Application.StartupPath & "\" & gstrMenuFile) = True) Then
                Dim file As System.IO.StreamReader
                file = New System.IO.StreamReader(Application.StartupPath & "\" & gstrMenuFile)
                line = file.ReadLine
                While (line <> Nothing)
                    Dim str() As String = line.Split("~")


                    If (line.IndexOf("~") < 0) Then

                        dt.Rows.Add(2, str(0).ToString(), 3, 3, 3, 0, "")

                    Else

                        '1-Add,Edit,Delete   a2-Add   e3-Edit  b4-Delete c5-Add,Edit    
                        If (RightString(line, 1) = "~") Then

                            dt.Rows.Add(2, str(0).ToString(), 2, 2, 2, 1, str(1).ToString())

                        ElseIf (RightString(line, 1) = "a") Then

                            dt.Rows.Add(2, str(0).ToString(), 2, 3, 3, 2, str(1).ToString())

                        ElseIf (RightString(line, 1) = "e") Then

                            dt.Rows.Add(2, str(0).ToString(), 3, 2, 3, 3, str(1).ToString())

                        ElseIf (RightString(line, 1) = "b") Then

                            dt.Rows.Add(2, str(0).ToString(), 3, 3, 2, 4, str(1).ToString())

                        ElseIf (RightString(line, 1) = "c") Then

                            dt.Rows.Add(2, str(0).ToString(), 2, 2, 3, 5, str(1).ToString())

                        End If

                    End If
                    line = file.ReadLine
                End While
                file.Close()
            End If

            grdRecords.BeginUpdate()
            grdRecords.DataSource = dt
            grdRecords.EndUpdate()


        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String
        Dim user_id As Integer
        Try
            blnSaveRecords = False

            If (txtLoginName.Text = "") Then

                MessageBox.Show("Specify login name", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtLoginName.Focus()
                Exit Function
            ElseIf (txtPassword.Text.Trim() = "") Then
                MessageBox.Show("Specify user password", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtPassword.Focus()
                Exit Function
            ElseIf (txtConfirmPassword.Text.Trim() = "") Then
                MessageBox.Show("Specify user password to confirm", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtConfirmPassword.Focus()
                Exit Function
            ElseIf (String.Compare(txtConfirmPassword.Text.Trim(), txtPassword.Text.Trim(), False) <> 0) Then
                MessageBox.Show("Password mismatch! /n Specify password again", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtPassword.Text = "" : txtConfirmPassword.Text = ""
                txtPassword.Focus()
                Exit Function
            ElseIf (txtPinNo.Text.Trim() = "") Then
                MessageBox.Show("Specify Pin No", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtPinNo.Focus()
                Exit Function
            ElseIf (txtFirstName.Text = "") Then
                MessageBox.Show("Specify first name", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtFirstName.Focus()
                Exit Function
            ElseIf (txtLastName.Text = "") Then
                MessageBox.Show("Specify last name", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtLastName.Focus()
                Exit Function
            ElseIf IsDBNullOrNothing(lkUserLevel.EditValue) Then
                MessageBox.Show("Specify user level", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lkUserLevel.Focus()
                Exit Function
            ElseIf IsDBNullOrNothing(txtEmailID.Text) Then
                MessageBox.Show("Specify Email Id", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtEmailID.Focus()
                Exit Function
            End If
            strQuery = "LoginName='" & Replace(Trim(txtLoginName.Text), "'", "''") & "'" & _
                                   IIf(mstrMode = "Edit", " and UserId<>" & Val(lkUserSelect.EditValue), "")
            If (strRecordID("tblUsers", "1", strQuery) <> "Null") Then
                MessageBox.Show("This login id already exists", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtLoginName.Focus()
                Exit Function
            End If
            If Val(lkUserLevel.EditValue) = 1 Then
                If (Val(strRecordID("tblUsers", "UserLevelId", "UserLevelId=1 and LoginName<>'" & Trim(txtLoginName.Text) & "'")) > 0) Then
                    MessageBox.Show("Doctor Admin already exists. Cannot add multiple Doctor Admin.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lkUserLevel.Focus()
                    Exit Function
                End If
            End If
            


            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " this record", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    txtLoginName.Focus()
                    Exit Function
                End If
            End If
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            If (mstrMode = "Add") Then
                user_id = lngAutogeneratePrimaryKey("tblUsers", "UserId")
                strQuery = "'" & Replace(Trim(txtFirstName.Text), "'", "''") & "'"
                strQuery = strQuery & ",'" & Replace(Trim(txtLastName.Text), "'", "''") & "'"
                strQuery = strQuery & ",'" & Replace(Trim(TEncrypt(txtPassword.Text)), "'", "''") & "'"
                strQuery = strQuery & "," & Val(lkUserLevel.EditValue)
                strQuery = strQuery & ",'" & Replace(Trim(txtLoginName.Text), "'", "''") & "'"
                strQuery = strQuery & ",Null,0"
                strQuery = strQuery & "," & IIf(IsDBNullOrNothing(txtQualification.Text) = True, "Null", "'" & Replace(Trim(txtQualification.Text), "'", "''") & "'")
                strQuery = strQuery & "," & IIf(chkActive.Checked = True, "1", "0")
                strQuery = strQuery & ",'" & Replace(Trim(txtEmailID.Text), "'", "''") & "'"
                strQuery = strQuery & ",'" & Replace(Trim(TEncrypt(txtPinNo.Text)), "'", "''") & "'"
                InsertintoTable("tblUsers", strQuery)
                If Val(lkUserLevel.EditValue) = 1 Or Val(lkUserLevel.EditValue) = 2 Then
                    Dim userId As Integer = Val(strRecordID("tblUsers", "MAX(UserId)", "UserId>0"))
                    strQuery = userId & ",Null,Null,Null"
                    strQuery = strQuery & ",1,1,1"
                    strQuery = strQuery & ",Null,Null,Null"
                    strQuery = strQuery & ",1,1,45"
                    Call InsertintoTable("tblPracticeInfo", strQuery)
                End If
            ElseIf (mstrMode = "Edit") Then
                user_id = lkUserSelect.EditValue
                strQuery = "FirstName='" & Replace(Trim(txtFirstName.Text), "'", "''") & "'"
                strQuery = strQuery & ",LastName='" & Replace(Trim(txtLastName.Text), "'", "''") & "'"
                strQuery = strQuery & ",Password='" & Replace(Trim(TEncrypt(txtPassword.Text)), "'", "''") & "'"
                strQuery = strQuery & ",UserLevelId=" & Val(lkUserLevel.EditValue) & ""
                strQuery = strQuery & ",LoginName='" & Replace(Trim(txtLoginName.Text), "'", "''") & "'"
                strQuery = strQuery & ",Qualifications=" & IIf(IsDBNullOrNothing(txtQualification.Text) = True, "Null", "'" & Replace(Trim(txtQualification.Text), "'", "''") & "'")
                strQuery = strQuery & ",UserStatus=" & IIf(chkActive.Checked = True, "1", "0")
                strQuery = strQuery & ",EmailId='" & Replace(Trim(txtEmailID.Text), "'", "''") & "'"
                strQuery = strQuery & ",PinNo='" & Replace(Trim(TEncrypt(txtPinNo.Text)), "'", "''") & "'"
                UpdateTable("tblUsers", strQuery, "UserId=" & user_id)
            End If

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function

    Private Sub frmMasterCompanyDetails_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If blnKeyTrap(e.KeyCode, Me, True, lkUserSelect) = True Then Exit Sub

        If e.KeyCode = Keys.F5 Then
            Dim intID As Int64 = 0
            Dim intRowID As Int32 = 0
            If (gdvRecords.RowCount > 0) Then
                intID = lngGetSelectID(gdvRecords)
            End If


            pbRecords.Position = 0
            pbRecords.Visible = True
            pbRecords.BringToFront()
            Application.DoEvents()
            pbRecords.Position = 20
            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
            '////PopulateData();
            pbRecords.Position = 95
            If (gdvRecords.RowCount > 0) Then
                intRowID = LocateRowBySingleValue(grdRecords, intID)
                gdvRecords.FocusedRowHandle = intRowID
            Else
                btnCancel_Click(Nothing, Nothing)
            End If
            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus
            pbRecords.Position = 100
            pbRecords.Visible = False
        End If
    End Sub

    Private Sub frmMasterCompanyDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgMDIForm.Images(91), Bitmap).GetHicon())

            Call GetAccessPermission(Me, "frmUtilityUserAcces")
            Call setPBRecords(Me, pbRecords)

            mblnActivate = True
            mblnChanged = False
            Me.Text = "User Access Previledges"

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub DisplayData(ByVal mlngUserPK As Integer)
        Dim dsTemp As DataSet
        Dim dsTemp1 As DataSet
        Try

            populateInGrid()

            dsTemp = FillDataSet("select * from tblUsers where UserId = " & mlngUserPK)

            If (dsTemp.Tables(0).Rows.Count > 0) Then
                txtFirstName.Text = dsTemp.Tables(0).Rows(0).Item("FirstName")
                txtLastName.Text = dsTemp.Tables(0).Rows(0).Item("LastName")
                txtPassword.Text = TDecrypt((dsTemp.Tables(0).Rows(0).Item("Password")).ToString)
                txtConfirmPassword.Text = TDecrypt((dsTemp.Tables(0).Rows(0).Item("Password")).ToString)
                lkUserLevel.EditValue = CInt(dsTemp.Tables(0).Rows(0).Item("UserLevelId"))
                txtLoginName.Text = dsTemp.Tables(0).Rows(0).Item("LoginName")
                If IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("Qualifications")) Then
                    txtQualification.Text = Nothing
                Else
                    txtQualification.Text = dsTemp.Tables(0).Rows(0).Item("Qualifications")
                End If
                chkActive.Checked = CBool(dsTemp.Tables(0).Rows(0).Item("UserStatus"))
                txtEmailID.Text = Trim(dsTemp.Tables(0).Rows(0).Item("EmailId") & "")
                If IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("PinNo")) Then
                    txtPinNo.Text = Nothing
                Else
                    txtPinNo.Text = TDecrypt(dsTemp.Tables(0).Rows(0).Item("PinNo").ToString)
                End If

                '//'If Administrator/p then some controls are deactived.
                'If ((dsTemp.Tables(0).Rows(0).Item("LoginName")).ToString() = "p" Or (dsTemp.Tables(0).Rows(0).Item("LoginName")).ToString() = "Admin") Then
                '    EnableDisableControls(False)
                'Else
                '    EnableDisableControls(True)
                'End If
                dsTemp1 = FillDataSet("SELECT * FROM utility_user_access WHERE user_pk=" & mlngUserPK)

                If (dsTemp1.Tables(0).Rows.Count > 0) Then
                    For i As Integer = 0 To gdvRecords.RowCount - 1
                        For Each row As DataRow In dsTemp1.Tables(0).Rows
                            If ((gdvRecords.GetRowCellValue(i, FormText).ToString()) = (row.Item("form_name")).ToString()) Then
                                '                                    //1-Add,Edit,Delete   a2-Add   e3-Edit  b4-Delete c5-Add,Edit  
                                If ((gdvRecords.GetRowCellValue(i, Group).ToString()) = "1") Then
                                    If (CBool(row.Item("add_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Add, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Add, 2)
                                    End If

                                    If (CBool(row.Item("edit_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Edit, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Edit, 2)
                                    End If

                                    If (CBool(row.Item("delete_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Delete, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Delete, 2)
                                    End If

                                ElseIf ((gdvRecords.GetRowCellValue(i, Group).ToString()) = "2") Then

                                    If (CBool(row.Item("add_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Add, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Add, 2)
                                    End If
                                    gdvRecords.SetRowCellValue(i, Edit, 3)
                                    gdvRecords.SetRowCellValue(i, Delete, 3)

                                ElseIf ((gdvRecords.GetRowCellValue(i, Group).ToString()) = "3") Then

                                    If (CBool(row.Item("edit_lev")) = True) Then

                                        gdvRecords.SetRowCellValue(i, Edit, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else

                                        gdvRecords.SetRowCellValue(i, Edit, 2)
                                    End If
                                    gdvRecords.SetRowCellValue(i, Delete, 3)
                                    gdvRecords.SetRowCellValue(i, Add, 3)

                                ElseIf ((gdvRecords.GetRowCellValue(i, Group).ToString()) = "4") Then
                                    If (CBool(row.Item("delete_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Delete, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Delete, 2)
                                    End If
                                    gdvRecords.SetRowCellValue(i, Add, 3)
                                    gdvRecords.SetRowCellValue(i, Edit, 3)

                                ElseIf ((gdvRecords.GetRowCellValue(i, Group).ToString()) = "5") Then

                                    If (CBool(row.Item("add_lev")) = True) Then
                                        gdvRecords.SetRowCellValue(i, Add, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)
                                    Else
                                        gdvRecords.SetRowCellValue(i, Add, 2)
                                    End If
                                    If (CBool(row.Item("edit_lev")) = True) Then

                                        gdvRecords.SetRowCellValue(i, Edit, 1)
                                        gdvRecords.SetRowCellValue(i, FormSet, 1)

                                    Else
                                        gdvRecords.SetRowCellValue(i, Edit, 2)
                                    End If
                                    gdvRecords.SetRowCellValue(i, Delete, 3)
                                End If
                            End If
                        Next
                    Next
                End If
            End If
            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call EnableDisableControls(True)
        Call DisplayData(lkUserSelect.Properties.GetKeyValueByDisplayText(lkUserSelect.Text))
        Me.Text = "User Access Details"
        mstrMode = ""
        mblnChanged = False
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then btnAdd.Enabled = blnEnable
        If blnEdit = True Then btnEdit.Enabled = blnEnable
        If blnDelete = True Then btnDelete.Enabled = blnEnable
        If blnAdd = True Or blnEdit = True Then btnSetAP.Enabled = blnEnable

        btnSave.Enabled = Not (blnEnable) : btnCancel.Enabled = Not (blnEnable)

        grbControl.Enabled = Not (blnEnable)
    End Sub

    Private Sub gdvRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.GotFocus
        If btnCancel.Enabled = True And Me.Visible = True Then Call btnCancel_Click(Nothing, Nothing)
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim blnTrnasaction As Boolean

        Try

            If Trim(lkUserSelect.Text) = "Admin" Or Trim(lkUserSelect.Text) = "p" Then
                MessageBox.Show("This user can't be deleted!", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
            If MessageBox.Show("Are you sure you want to permanently delete this user?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True

                Call DeleteFromTable("tblUsers", "UserId=" & Val(lkUserSelect.Properties.GetKeyValueByDisplayText(lkUserSelect.Text)))

                gtrnWebPlusMed.Commit()
                blnTrnasaction = False

                MessageBox.Show("User deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)

                PopulateLookupDX(lkUserSelect, "Login Name", "UserId", "tblUsers", "UserId,LoginName [Login Name]", "", "LoginName", False, "", 200, False)
                'Check for login. If logged user is doctor then user level should be Nurse n Receptionist.
                Dim UserCriteria As String = IIf(gintUserLevelId = 2, " WHERE UserLevelId=3 OR UserLevelId=4 ", String.Empty)
                PopulateLookupDX(lkUserLevel, "User Level", "UserLevelId", "LtblUserLevel", "UserLevelId, UserLevel [User Level]", UserCriteria, "UserLevel")

                lkUserSelect.ItemIndex = 0
                lkUserSelect_TextChanged(sender, e)
            End If
        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Public Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            Call EnableDisableControls(False)
            Clearfields(grbControl)
            mstrMode = "Add"
            Me.Text = "User Access Details [Add]"
            txtLoginName.Focus()
            mblnChanged = False
            chkActive.Checked = True
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        'Dim lngTemp As Long, lngRowID As Long
        Dim strUser As String = txtLoginName.Text

        Try
            If blnSaveRecords() = False Then Exit Sub
            PopulateLookupDX(lkUserSelect, "Login Name", "UserId", "tblUsers", "UserId,LoginName [Login Name]", "", "LoginName", False, "", 200, False)
            'PopulateComboDX(cboUserLevel, "utility_user_master", "distinct user_department", "", False)
            'Check for login. If logged user is doctor then user level should be Nurse n Receptionist.
            Dim UserCriteria As String = IIf(gintUserLevelId = 2, " WHERE UserLevelId=3 OR UserLevelId=4 ", String.Empty)
            PopulateLookupDX(lkUserLevel, "User Level", "UserLevelId", "LtblUserLevel", "UserLevelId, UserLevel [User Level]", UserCriteria, "UserLevel")

            lkUserSelect.EditValue = mlngRecordID

            btnCancel_Click(Nothing, Nothing)
        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            Call EnableDisableControls(False)

            mblnChanged = False
            mstrMode = "Edit"
            Me.Text = "User Access Details [Edit]"
            If (txtLoginName.Enabled = True) Then
                txtLoginName.Focus()
            Else
                txtPassword.Focus()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnSetAP_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSetAP.Click
        Dim blnTransaction As Boolean
        Dim strQuery As String
        Try
            If MessageBox.Show("Are you sure to modify this user?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTransaction = True

                Call DeleteFromTable("utility_user_access", "user_pk=" & lkUserSelect.Properties.GetKeyValueByDisplayText(lkUserSelect.Text))

                For i As Integer = 0 To gdvRecords.RowCount - 1
                    If (gdvRecords.GetRowCellValue(i, Add).ToString() = "1") Or (gdvRecords.GetRowCellValue(i, Edit).ToString() = "1") Or (gdvRecords.GetRowCellValue(i, Delete).ToString() = "1") Then
                        If (gdvRecords.GetRowCellValue(i, Group).ToString() <> "0") Then
                            strQuery = lkUserSelect.Properties.GetKeyValueByDisplayText(lkUserSelect.Text).ToString()
                            strQuery = strQuery & ",'" & gdvRecords.GetRowCellValue(i, FormText).ToString().Replace("'", "''") & "'"
                            If (gdvRecords.GetRowCellValue(i, Add).ToString() = "1") Then
                                strQuery = strQuery + ",1"
                            Else
                                strQuery = strQuery + ",0"
                            End If
                            If (gdvRecords.GetRowCellValue(i, Edit).ToString() = "1") Then
                                strQuery = strQuery + ",1"
                            Else
                                strQuery = strQuery + ",0"
                            End If
                            If (gdvRecords.GetRowCellValue(i, Delete).ToString() = "1") Then
                                strQuery = strQuery + ",1"
                            Else
                                strQuery = strQuery + ",0"
                            End If

                            InsertintoTable("utility_user_access", strQuery)
                        End If
                    End If
                    
                Next
                gtrnWebPlusMed.Commit()
                blnTransaction = False
                mblnAccessChanged = False
                lkUserSelect_TextChanged(Nothing, Nothing)
                'MessageBox.Show("Assess privileges updated", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            If blnTransactionState() = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvRecords_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.Click
        If (gdvRecords.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Or gdvRecords.FocusedRowHandle = DevExpress.XtraGrid.GridControl.InvalidRowHandle) Then Exit Sub
        SetData(gdvRecords.FocusedRowHandle)
    End Sub

    Private Sub gdvRecords_RowCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles gdvRecords.RowCellStyle
        Dim view As DevExpress.XtraGrid.Views.Grid.GridView = sender
        ' DevExpress.XtraGrid.Views.Grid.GridView View = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
        If (e.RowHandle >= 0) Then
            Dim fnBold As System.Drawing.Font
            fnBold = New System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold)
            If (view.GetRowCellValue(e.RowHandle, Group).ToString() = "0") Then
                e.Appearance.BackColor = Color.LightCoral
                e.Appearance.Font = fnBold
            End If
        End If
    End Sub

    Private Sub lkUserSelect_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkUserSelect.TextChanged
        If (lkUserSelect.ItemIndex >= 0) Then btnCancel_Click(Nothing, Nothing)
    End Sub

    Private Sub chkActive_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles chkActive.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnSave.Focus()
        End If
    End Sub
End Class